﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace TimeControllerAdminApp
{
    public partial class FormAdminMain : Form
    {
        DataSet _EmployeeDS = null;
        DataSet _DepartmentDS = null;
        DataSet _VacationDS = null;
        DataSet _ActionDS = null;
        DataSet _ActionFlowDS = null;
        Boolean _LoadFinished = false;
        DataSet _EmployeeActionsDS = null;
        DataTable _EmployeeActionsDT = null;

        //TODO:This values must be set dynamically not statically
        //int _InMorning = 1;
        //int _InSpecialCustomerVendor = 2;
        //int _InSpecialPersonal = 3;
        //int _InSpecialGenDoctor = 4;
        //int _InSpecialSpeDoctor = 5;
        //int _InLunch = 6;
        //int _OutLunch = 7;
        //int _OutSpecialCustomerVendor = 8;
        //int _OutSpecialPersonal = 9;
        //int _OutSpecialGenDoctor = 10;
        //int _OutSpecialSpeDoctor = 11;
        //int _OutExit = 12;

        //System.Threading.Thread thread1 = null;


        public FormAdminMain()
        {
            InitializeComponent();
            //thread1 = new System.Threading.Thread(new System.Threading.ThreadStart(StartJob1));
            //thread1.Start();
        }


        private void FormAdminMain_Load(object sender, EventArgs e)
        {
            LoadEmployees();
            LoadDepartments();
            ButtonNewEmployee_Click(null, null);
            _LoadFinished = true;
        }

        private void LoadEmployees()
        {
            try
            {
                String sql = @"SELECT e.*, d.DepartmentName, s.StatusName, e2.NameSurname as ManagerName 
                               from Employees e LEFT OUTER JOIN Status s ON e.StatusID = s.StatusID 
                               LEFT OUTER JOIN Department d ON e.DepartmentID = d.DepartmentID
                               LEFT OUTER JOIN Employees e2 ON e.ManagerID = e2.EmployeeID and e2.IsDeleted = 0
                               WHERE e.IsDeleted = 0  ORDER BY e.NameSurname";
                _EmployeeDS = DB.Sorgula(sql, "");
                DataGridViewEmployee.Rows.Clear();
                if (_EmployeeDS != null && _EmployeeDS.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dr in _EmployeeDS.Tables[0].Rows)
                    {
                        String id = "";
                        String name = "";
                        String status = "";
                        String code = "";
                        String email = "";
                        String manager = "";
                        String department = "";
                        String phone = "";

                        id = dr["EmployeeID"].ToString();
                        name = dr["NameSurname"].ToString();
                        code = dr["Code"].ToString();
                        if (!dr["StatusName"].Equals(DBNull.Value))
                            status = dr["StatusName"].ToString();

                        if (!dr["Email"].Equals(DBNull.Value))
                            email = dr["Email"].ToString();
                        if (!dr["PhoneNumber"].Equals(DBNull.Value))
                            phone = dr["PhoneNumber"].ToString();
                        if (!dr["ManagerName"].Equals(DBNull.Value))
                            manager = dr["ManagerName"].ToString();
                        if (!dr["DepartmentName"].Equals(DBNull.Value))
                            department = dr["DepartmentName"].ToString();
                        DataGridViewEmployee.Rows.Add(id, name, status, code, email, phone, manager, department);
                    }
                    if (DataGridViewEmployee.SelectedRows.Count > 0)
                    {
                        DataGridViewEmployee.SelectedRows[0].Selected = false;
                    }
                    ComboBoxEmployeeManager.DisplayMember = "NameSurname";
                    ComboBoxEmployeeManager.ValueMember = "EmployeeID";
                    ComboBoxEmployeeManager.DataSource = _EmployeeDS.Tables[0];
                }
                

                
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception occured when loading Employees!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine(ex.StackTrace);
            }
        }

        private void LoadDepartments()
        {
            try
            {
                String sql = "SELECT * from dbo.Department ORDER BY DepartmentName";
                _DepartmentDS = DB.Sorgula(sql, "");
                
                ComboBoxEmployeeDept.DisplayMember = "DepartmentName";
                ComboBoxEmployeeDept.ValueMember = "DepartmentID";
                ComboBoxEmployeeDept.DataSource = _DepartmentDS.Tables[0];
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception occured when loading Departments!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine(ex.StackTrace);
            }
        }

        private void LoadActions()
        {
            try
            {
                String sql = "SELECT * from dbo.Actions";
                _ActionDS = DB.Sorgula(sql, "");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception occured when loading Actions!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine(ex.StackTrace);
            }
        }

        private void LoadActionFlows()
        {
            try
            {
                String sql = "SELECT * from dbo.ActionFlow";
                _ActionFlowDS = DB.Sorgula(sql, "");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception occured when loading ActionFlow!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine(ex.StackTrace);
            }
        }

        private void LoadEmptyPossibleActions()
        {
            DataGridViewPossibleActions.Rows.Clear();
            foreach (DataRow dr in _ActionDS.Tables[0].Rows)
            {
                DataGridViewPossibleActions.Rows.Add(dr["ActionID"].ToString(), false, dr["ActionName"].ToString());
            }
            if (DataGridViewPossibleActions.SelectedRows.Count > 0)
                DataGridViewPossibleActions.SelectedRows[0].Selected = false;
        }

        private void LoadPossibleActions(String actionId)
        {
            try
            {
                String sql = "SELECT * from dbo.ActionFlow WHERE FirstActionID = " + actionId;
                DataSet ds = DB.Sorgula(sql, "");
                if (ds == null) throw new Exception("");
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    foreach (DataGridViewRow dgvr in DataGridViewPossibleActions.Rows)
                    {
                        if (dgvr.Cells[0].Value.ToString().Equals(dr["NextActionID"].ToString()))
                        {
                            DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)dgvr.Cells[1];
                            cell.Value = true;
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception occured when loading Actions!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine(ex.StackTrace);
            }
        }


        private void DataGridViewEmployee_SelectionChanged(object sender, EventArgs e)
        {
            if (!_LoadFinished) return;
            ComboBoxEmployeeDept.SelectedIndex = -1;
            ComboBoxEmployeeManager.SelectedIndex = -1;
            if (DataGridViewEmployee.SelectedRows.Count == 0)
                return;

            string EmployeeID = DataGridViewEmployee.SelectedRows[0].Cells[0].Value.ToString();
            foreach (DataRow dr in _EmployeeDS.Tables[0].Rows)
            {
                if (dr["EmployeeID"].ToString().Equals(EmployeeID))
                {
                    TextBoxEmployeeName.Text = dr["NameSurname"].ToString();
                    TextBoxEmployeeCode.Text = dr["Code"].ToString();
                    TextBoxEmployeeEmail.Text = dr["Email"].ToString();
                    TextBoxEmployeePhone.Text = dr["PhoneNumber"].ToString();
                    DateTimePickerHireDate.Value = Convert.ToDateTime(dr["HireDate"]);
                    if (dr["AnnualVacationLimit"] != null)
                        NumericUpDownVacLimit.Value = Convert.ToInt32(dr["AnnualVacationLimit"]);
                    else
                        NumericUpDownVacLimit.Value = 0;

                    if (dr["DepartmentID"] != DBNull.Value && _DepartmentDS != null)
                    {
                        foreach (DataRow drd in _DepartmentDS.Tables[0].Rows)
                        {
                            if (drd["DepartmentID"].ToString().Equals(dr["DepartmentID"].ToString()))
                            {
                                ComboBoxEmployeeDept.SelectedValue = Convert.ToInt32(drd["DepartmentID"].ToString());
                                break;
                            }
                        }
                    }
                    if (dr["ManagerID"] != DBNull.Value)
                    {
                        foreach (DataRow dre in _EmployeeDS.Tables[0].Rows)
                        {
                            if (dre["EmployeeID"].ToString().Equals(dr["ManagerID"].ToString()))
                            {
                                ComboBoxEmployeeManager.SelectedValue = Convert.ToInt32(dre["EmployeeID"].ToString());
                                break;
                            }
                        }
                    }
                    LoadVacations(EmployeeID);
                    break;
                }
            }
        }

        private void ButtonNewEmployee_Click(object sender, EventArgs e)
        {
            TextBoxEmployeeName.Text = "";
            TextBoxEmployeeCode.Text = "";
            TextBoxEmployeeEmail.Text = "";
            TextBoxEmployeePhone.Text = "";
            NumericUpDownVacLimit.Value = 0;
            ComboBoxEmployeeDept.SelectedIndex = -1;
            ComboBoxEmployeeManager.SelectedIndex = -1;
            if (DataGridViewEmployee.SelectedRows.Count > 0)
                DataGridViewEmployee.SelectedRows[0].Selected = false;
        }

        private void ButtonSaveEmployee_Click(object sender, EventArgs e)
        {
            TextBoxEmployeeName.Text = Utility.InputFilter(TextBoxEmployeeName.Text);
            TextBoxEmployeeCode.Text = Utility.InputFilter(TextBoxEmployeeCode.Text);
            TextBoxEmployeeEmail.Text = Utility.InputFilter(TextBoxEmployeeEmail.Text);
            TextBoxEmployeePhone.Text = Utility.InputFilter(TextBoxEmployeePhone.Text);

            if (TextBoxEmployeeName.Text == "" || TextBoxEmployeeCode.Text == "")
            {
                MessageBox.Show("Employee name&surname and code must be filled!", "Save Employee", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (DataGridViewEmployee.SelectedRows.Count == 0) //insert
            {
                string sorgu = "INSERT INTO Employees(Code, NameSurname, Email, PhoneNumber, AnnualVacationLimit, HireDate";
                string values = " VALUES('" + TextBoxEmployeeCode.Text + "', " +
                                "'" + TextBoxEmployeeName.Text + "', " +
                                "'" + TextBoxEmployeeEmail.Text + "', " +
                                "'" + TextBoxEmployeePhone.Text + "', " +
                                NumericUpDownVacLimit.Value.ToString() + ", " +
                                "'" + String.Format(@"{0:yyyy-MM-dd HH:mm:ss}", DateTimePickerHireDate.Value) + "'";
                if(ComboBoxEmployeeDept.SelectedIndex > 0 && Convert.ToInt32(ComboBoxEmployeeDept.SelectedValue) > 0)
                {
                    sorgu += ", DepartmentID";
                    values += ", " + Convert.ToInt32(ComboBoxEmployeeDept.SelectedValue);
                }
                if(ComboBoxEmployeeManager.SelectedIndex > 0 && Convert.ToInt32(ComboBoxEmployeeManager.SelectedValue) > 0)
                {
                    sorgu += ", ManagerID";
                    values += ", " + Convert.ToInt32(ComboBoxEmployeeManager.SelectedValue);
                }
                sorgu = sorgu + ")" + values + ")";
                try
                {
                    if (DB.Uygula(sorgu, "ButtonSaveEmployee_Click"))
                    {
                        MessageBox.Show("Employee saved.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LoadEmployees();
                        DataSet ds = DB.Sorgula("SELECT MAX(EmployeeId) FROM Employees", "ButtonSaveEmployee_Click");
                        string id = ds.Tables[0].Rows[0][0].ToString();
                        foreach (DataGridViewRow dgrv in DataGridViewEmployee.Rows)
                        {
                            if (dgrv.Cells[0].Value.ToString() == id)
                            {
                                dgrv.Selected = true;
                                DataGridViewEmployee.FirstDisplayedScrollingRowIndex = dgrv.Index;
                                return;
                            }
                        }
                    }
                    else
                        throw new Exception("");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Exception occured while saving Employee!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Console.WriteLine(ex.StackTrace);
                }
            }
            else//update
            {
                string EmployeeID = DataGridViewEmployee.SelectedRows[0].Cells[0].Value.ToString();
                string sorgu = "UPDATE Employees SET NameSurname = '" + TextBoxEmployeeName.Text +
                    "', Code = '" + TextBoxEmployeeCode.Text +
                    "', Email = '" + TextBoxEmployeeEmail.Text +
                    "', AnnualVacationLimit = " + NumericUpDownVacLimit.Value.ToString() +
                    ", HireDate = '" + String.Format(@"{0:yyyy-MM-dd HH:mm:ss}", DateTimePickerHireDate.Value) + "'" +
                    ", PhoneNumber = '" + TextBoxEmployeePhone.Text + "'";
                if (ComboBoxEmployeeDept.SelectedIndex != -1 && Convert.ToInt32(ComboBoxEmployeeDept.SelectedValue) > 0)
                {
                    sorgu += ", DepartmentID = " + Convert.ToInt32(ComboBoxEmployeeDept.SelectedValue);
                }
                else
                {
                    sorgu += ", DepartmentID = NULL";
                }
                if (ComboBoxEmployeeManager.SelectedIndex != -1 && Convert.ToInt32(ComboBoxEmployeeManager.SelectedValue) > 0)
                {
                    sorgu += ", ManagerID = " + Convert.ToInt32(ComboBoxEmployeeManager.SelectedValue);
                }
                else
                {
                    sorgu += ", ManagerID = NULL";
                }
                sorgu += " WHERE EmployeeID = " + EmployeeID;
                try
                {
                    if (DB.Uygula(sorgu, "ButtonSaveEmployee_Click"))
                    {
                        MessageBox.Show("Employee updated.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LoadEmployees();
                        foreach (DataGridViewRow dgrv in DataGridViewEmployee.Rows)
                        {
                            if (dgrv.Cells[0].Value.ToString() == EmployeeID)
                            {
                                dgrv.Selected = true;
                                DataGridViewEmployee.FirstDisplayedScrollingRowIndex = dgrv.Index;
                                return;
                            }
                        }
                    }
                    else throw new Exception("");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error occured while updating Employee!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Console.WriteLine(ex.StackTrace);
                }
            }
        }

        private void ButtonDeleteEmployee_Click(object sender, EventArgs e)
        {
            if (DataGridViewEmployee.SelectedRows.Count == 0)
            {
                MessageBox.Show("You must select an Employee", "Delete Employee", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            DialogResult result = MessageBox.Show("Are you sure that you want to delete the Employee?", "Delete Employee", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result != DialogResult.Yes) return;

            string EmployeeId = DataGridViewEmployee.SelectedRows[0].Cells[0].Value.ToString();
            try
            {
                string sorgu = "UPDATE Employees SET IsDeleted = 1 WHERE EmployeeID = " + EmployeeId;
                if (DB.Uygula(sorgu, "ButtonDeleteEmployee_Click"))
                {
                    MessageBox.Show("Employee deleted.", "Delete Employee", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    LoadEmployees();
                    ButtonNewEmployee_Click(null, null);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occured while updating Employee!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine(ex.StackTrace);
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 1)
                FillDateGrid();
            else if (tabControl1.SelectedIndex == 2)
            {
                InOutTabLoad();
            }
            else if (tabControl1.SelectedIndex == 3)
            {
                DataGridViewActions.Rows.Clear();
                LoadActions();
                foreach (DataRow dr in _ActionDS.Tables[0].Rows)
                {
                    DataGridViewActions.Rows.Add(dr["ActionID"].ToString(), dr["ActionName"].ToString());
                }
                if (DataGridViewActions.SelectedRows.Count > 0)
                    DataGridViewActions.SelectedRows[0].Selected = false;
                DataGridViewPossibleActions.Rows.Clear();
            }
        }

        private void InOutTabLoad()
        {
            LoadActions();
            LoadEmployees();
            if (_EmployeeDS != null && _EmployeeDS.Tables[0].Rows.Count > 0)
            {
                DataGridViewEmployeeList.Rows.Clear();
                foreach (DataRow dr in _EmployeeDS.Tables[0].Rows)
                {
                    String id = "";
                    String name = "";
                    String status = "";

                    id = dr["EmployeeID"].ToString();
                    name = dr["NameSurname"].ToString();

                    if (!dr["StatusName"].Equals(DBNull.Value))
                        status = dr["StatusName"].ToString();

                    DataGridViewEmployeeList.Rows.Add(id, name, status);
                }
                if (DataGridViewEmployeeList.SelectedRows.Count > 0)
                {
                    DataGridViewEmployeeList.SelectedRows[0].Selected = false;
                }
            }
        }

        private void FillDateGrid()
        {
            DataGridViewDateOfDays.Rows.Clear();
            DateTime firstDayOfTheThisMonth = Utility.GetFirstDayOfThisMonth();
            DateTime firstDayOfThePreviousMonth = firstDayOfTheThisMonth.AddMonths(-1);
            DateTime firstDayOfTheNextMonth = firstDayOfTheThisMonth.AddMonths(1);

            for (DateTime date = firstDayOfThePreviousMonth; date < firstDayOfTheNextMonth.AddMonths(1); date = date.AddDays(1))
            {
                CheckIfDateExistsInTable(date);
            }
            try
            {
                String sql = "SELECT * from DateOfDays ORDER BY DateOfDay DESC";
                DataSet ds = DB.Sorgula(sql, "FillDateGrid");
                if (ds == null)
                    throw new Exception("");
                foreach(DataRow dr in ds.Tables[0].Rows)
                {
                    DateTime date = Convert.ToDateTime(dr["DateOfDay"].ToString());
                    DataGridViewDateOfDays.Rows.Add(dr["DateOfDayID"].ToString(), 
                                                    date.ToLongDateString(), 
                                                    Convert.ToBoolean(dr["IsFullDay"].ToString()), 
                                                    Convert.ToBoolean(dr["IsHalfDay"].ToString()), 
                                                    Convert.ToBoolean(dr["IsHoliday"].ToString()), 
                                                    dr["LabourMinutes"].ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occured while filling the calendar!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine(ex.StackTrace);
            }
        }

        private bool CheckIfDateExistsInTable(DateTime date)
        {
            try
            {
                string sorgu = "SELECT * FROM DateOfDays where YEAR(DateOfDay) = " + date.Year + " AND MONTH(DateOfDay) = " + date.Month + " AND DAY(DateOfDay) = " + date.Day;
                DataSet ds = DB.Sorgula(sorgu, "CheckIfDateExistsInTable");
                if (ds != null && ds.Tables[0].Rows.Count == 0)
                {
                    string sql = "INSERT INTO DateOfDays(DateOfDay, IsFullDay, IsHalfDay, IsHoliday) VALUES(";
                    sql += "'" + date.Year + "-" + date.Month + "-" + date.Day + "', 0, 0, 0)";
                    if (!DB.Uygula(sql, "CheckIfDateExistsInTable"))
                    {
                        throw new Exception("");
                    }
                    return true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occured while checking dates!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine(ex.StackTrace);
            }
            return false;
        }

        private void DataGridViewDateOfDays_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                DayTypeContextMenuStrip.Show(DataGridViewDateOfDays, e.Location);
            }
        }

        private void DataGridViewDateOfDays_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1 || e.ColumnIndex == -1 || e.ColumnIndex == 0 || e.ColumnIndex == 1) return;

            if (e.ColumnIndex == 2 || e.ColumnIndex == 3 || e.ColumnIndex == 4)
            {
                DataGridViewCheckBoxCell curCell = (DataGridViewCheckBoxCell)DataGridViewDateOfDays.Rows[e.RowIndex].Cells[e.ColumnIndex];
                ((DataGridViewCheckBoxCell)curCell.OwningRow.Cells[2]).Value = false;
                ((DataGridViewCheckBoxCell)curCell.OwningRow.Cells[3]).Value = false;
                ((DataGridViewCheckBoxCell)curCell.OwningRow.Cells[4]).Value = false;
            }
            else if (e.ColumnIndex == 5)
            {
                DataGridViewTextBoxCell curCell = (DataGridViewTextBoxCell)DataGridViewDateOfDays.Rows[e.RowIndex].Cells[5];
                //((DataGridViewTextBoxCell)curCell.OwningRow.Cells[5]).Value = 0;
            }
        }

        private void DataGridViewDateOfDays_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            String dayId="";
            int val=0;
            int minutes=0;
            if (e.RowIndex == -1 || e.ColumnIndex == -1) return;

            if (e.ColumnIndex == 2 || e.ColumnIndex == 3 || e.ColumnIndex == 4)
            {
                DataGridViewCheckBoxCell curCell = (DataGridViewCheckBoxCell)DataGridViewDateOfDays.Rows[e.RowIndex].Cells[e.ColumnIndex];
                dayId = curCell.OwningRow.Cells[0].Value.ToString();
                val = Convert.ToInt32(curCell.Value);
            }
            else if (e.ColumnIndex == 5)
            {
                DataGridViewTextBoxCell LabourMinutes = (DataGridViewTextBoxCell)DataGridViewDateOfDays.Rows[e.RowIndex].Cells["LabourMinutes"];
                dayId = LabourMinutes.OwningRow.Cells[0].Value.ToString();
                minutes = Convert.ToInt32(LabourMinutes.Value);
            }
           
            
            try
            {
                String columnName = "";
                if (e.ColumnIndex == 2) columnName = "IsFullDay";
                else if (e.ColumnIndex == 3) columnName = "IsHalfDay";
                else if (e.ColumnIndex == 4) columnName = "IsHoliday";
                String sqlUpdate = "UPDATE DATEOFDAYS SET " + columnName + " = " + val.ToString() + " WHERE DateOfDayID = " + dayId;

                if (e.ColumnIndex == 5) 
                {
                    columnName = "LabourMinutes";
                    sqlUpdate = "UPDATE DATEOFDAYS SET " + columnName + " = " + (int)minutes + " WHERE DateOfDayID = " + dayId;
                }

                if (!DB.Uygula(sqlUpdate, ""))
                {
                    throw new Exception("DataGridViewDateOfDays_CellValueChanged");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occured while updating the values!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine(ex.StackTrace);
            }
        }

        private void fullDayToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetDayTypeOfSelectedRows(true, false, false);
        }

        private void halfDayToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetDayTypeOfSelectedRows(false, true, false);
        }

        private void holidayToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetDayTypeOfSelectedRows(false, false, true);
        }

        private void SetDayTypeOfSelectedRows(bool isFullDay, bool isHalfDay, bool isHoliday)
        {
            if (DataGridViewDateOfDays.SelectedRows.Count == 0) return;

            for (int i = 0; i < DataGridViewDateOfDays.SelectedRows.Count; i++)
            {
                DataGridViewDateOfDays.SelectedRows[i].Cells[2].Value = isFullDay;
                DataGridViewDateOfDays.SelectedRows[i].Cells[3].Value = isHalfDay;
                DataGridViewDateOfDays.SelectedRows[i].Cells[4].Value = isHoliday;
            }
        }

        private void ButtonNewVacation_Click(object sender, EventArgs e)
        {
            if (DataGridViewEmployeeVacations.SelectedRows.Count > 0)
                DataGridViewEmployeeVacations.SelectedRows[0].Selected = false;
            DateTimePickerVacationFrom.Value = DateTime.Now;
            DateTimePickerVacationTo.Value = DateTime.Now;
        }

        private void ButtonSaveVacation_Click(object sender, EventArgs e)
        {
            if (DataGridViewEmployee.SelectedRows.Count == 0)
            {
                MessageBox.Show("You must select an employee first!", "Save Vacation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            DateTime fromDate = DateTimePickerVacationFrom.Value;
            DateTime toDate = DateTimePickerVacationTo.Value;
            fromDate = new DateTime(fromDate.Year, fromDate.Month, fromDate.Day, 0, 0, 0);
            toDate = new DateTime(toDate.Year, toDate.Month, toDate.Day, 0, 0, 0);
            if (fromDate.CompareTo(toDate) >= 0)
            {
                MessageBox.Show("'From Date' must be less than 'To Date' at least one day", "Save Vacation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //select holidays in current year
            String ss = "SELECT * FROM DateOfDays where YEAR(DateOfDay) = " + DateTime.Now.Year + " AND IsHoliday = 1";
            ArrayList availableDays = new ArrayList();
            try
            {
                DataSet ds = DB.Sorgula(ss, "ButtonSaveVacation_Click");
                if (ds == null) throw new Exception("");
                
                for (DateTime d = fromDate; d < toDate; d = d.AddDays(1))
                {
                    //check if the vacationdate is holiday
                    DataRow[] drs = ds.Tables[0].Select("DateOfDay = '" + String.Format("{0:yyyy-MM-dd 00:00:00}", d) + "'");
                    if (drs.Length == 0)
                        availableDays.Add(d);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception occured while saving vacation!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine(ex.StackTrace);
            }

            if (Convert.ToInt32(LabelRemDayCount.Text) < availableDays.Count)
            {
                MessageBox.Show("Annual Vacation Date Limit Exceeded!", "Save Vacation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }


            String EmployeeID = DataGridViewEmployee.SelectedRows[0].Cells[0].Value.ToString();
            if (DataGridViewEmployeeVacations.SelectedRows.Count == 0)//insert
            {
                ArrayList sqlArray = new ArrayList();
                foreach(DateTime date in availableDays)
                {
                    String sql = "INSERT INTO EmployeeVacations(EmployeeID, VacationDate) VALUES (";
                    sql += EmployeeID + ", ";
                    sql += "'" + date.Year + "-" + date.Month + "-" + date.Day + "');";
                    sqlArray.Add(sql);
                }
                try
                {
                    if (DB.UygulaTrans(sqlArray.ToArray(), "ButtonSaveVacation_Click"))
                    {
                        MessageBox.Show("Employee vacation saved.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LoadVacations(EmployeeID);
                        /*
                        DataSet ds = DB.Sorgula("SELECT MAX(EmployeeVacationID) FROM EmployeeVacations", "ButtonSaveVacation_Click");
                        string id = ds.Tables[0].Rows[0][0].ToString();
                        foreach (DataGridViewRow dgrv in DataGridViewEmployeeVacations.Rows)
                        {
                            if (dgrv.Cells[0].Value.ToString() == id)
                            {
                                dgrv.Selected = true;
                                DataGridViewEmployeeVacations.FirstDisplayedScrollingRowIndex = dgrv.Index;
                                return;
                            }
                        }*/
                    }
                    else
                        throw new Exception("");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Exception occured while saving vacation!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Console.WriteLine(ex.StackTrace);
                }
            }
            else//update
            {
                try
                {
                    String vacationID = DataGridViewEmployeeVacations.SelectedRows[0].Cells[0].Value.ToString();
                        
                    String sorgu = "UPDATE EmployeeVacations SET ";
                    sorgu += "VacationDateFrom = '" + fromDate.Year + "-" + fromDate.Month + "-" + fromDate.Day + "', ";
                    sorgu += "VacationDateTo = '" + toDate.Year + "-" + toDate.Month + "-" + toDate.Day + "' ";
                    sorgu += "WHERE EmployeeVacationID = " + vacationID;
                    if (DB.Uygula(sorgu, "ButtonSaveVacation_Click"))
                    {
                        MessageBox.Show("Vacation updated.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LoadVacations(EmployeeID);
                        foreach (DataGridViewRow dgrv in DataGridViewEmployeeVacations.Rows)
                        {
                            if (dgrv.Cells[0].Value.ToString() == vacationID)
                            {
                                dgrv.Selected = true;
                                DataGridViewEmployeeVacations.FirstDisplayedScrollingRowIndex = dgrv.Index;
                                return;
                            }
                        }
                    }
                    else throw new Exception("");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error occured while updating vacation!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Console.WriteLine(ex.StackTrace);
                }
            }
        }

        private void LoadVacations(String EmployeeID)
        {
            DataGridViewEmployeeVacations.Rows.Clear();
            try
            {
                int currentYear = DateTime.Now.Year;
                String firstDatOfTheYear = currentYear + "-01-01 00:00:00";
                String lastDatOfTheYear = currentYear + "-12-31 23:59:59";
                String sql = "SELECT * from dbo.EmployeeVacations WHERE EmployeeID = " + EmployeeID + " AND VacationDate BETWEEN '" + firstDatOfTheYear + "' AND '" + lastDatOfTheYear + "' ORDER BY VacationDate desc";
                _VacationDS = DB.Sorgula(sql, "");

                if (_VacationDS == null) throw new Exception("");

                if (_VacationDS.Tables[0].Rows.Count == 1)
                {
                    DataRow dr = _VacationDS.Tables[0].Rows[0];
                    DataGridViewEmployeeVacations.Rows.Add(
                        dr["EmployeeVacationID"].ToString(), 
                        String.Format("{0:yyyy.MM.dd}", Convert.ToDateTime(dr["VacationDate"].ToString())), 
                        String.Format("{0:yyyy.MM.dd}", Convert.ToDateTime(dr["VacationDate"].ToString()).AddDays(1)), 1);
                }
                else if (_VacationDS.Tables[0].Rows.Count > 1)
                {
                    DateTime fromDate = DateTime.MinValue;
                    DateTime toDate = DateTime.MinValue;
                    //DateTime date = DateTime.MinValue;
                    foreach (DataRow dr in _VacationDS.Tables[0].Rows)
                    {
                        if (toDate.Equals(DateTime.MinValue))
                        {
                            toDate = Convert.ToDateTime(dr["VacationDate"].ToString()).AddDays(1);
                            fromDate = Convert.ToDateTime(dr["VacationDate"].ToString());
                            continue;
                        }

                        DateTime tempDate = Convert.ToDateTime(dr["VacationDate"].ToString());
                        if (!tempDate.Date.Equals(fromDate.AddDays(-1).Date))
                        {
                            DataGridViewEmployeeVacations.Rows.Add(dr["EmployeeVacationID"].ToString(), String.Format("{0:yyyy.MM.dd}", fromDate), String.Format("{0:yyyy.MM.dd}", toDate), toDate.Subtract(fromDate).Days);
                            toDate = tempDate.AddDays(1);
                            fromDate = tempDate;
                        }else
                            fromDate = fromDate.AddDays(-1); 
                    }
                    if (!fromDate.Equals(DateTime.MinValue))
                    {
                        DataGridViewEmployeeVacations.Rows.Add(_VacationDS.Tables[0].Rows[_VacationDS.Tables[0].Rows.Count-1]["EmployeeVacationID"].ToString(),
                            String.Format("{0:yyyy.MM.dd}", fromDate), 
                            String.Format("{0:yyyy.MM.dd}", toDate), 
                            toDate.Subtract(fromDate).Days);
                    }
                }
                CalculateRemainingVacations();
                ButtonNewVacation_Click(null, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception occured when loading employee vacations!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine(ex.StackTrace);
            }
        }

        private void CalculateRemainingVacations()
        {
            int usedVacations = 0;
            int remainingVacations = 0;
            int totalVacations = 0;
            LabelUsedDayCount.Text = usedVacations.ToString();
            LabelRemDayCount.Text = remainingVacations.ToString();
            if (DataGridViewEmployee.SelectedRows.Count == 0)
                return;

            if (DataGridViewEmployeeVacations.Rows.Count > 0)
            {
                foreach (DataGridViewRow dgvr in DataGridViewEmployeeVacations.Rows)
                {
                    usedVacations += Convert.ToInt32(dgvr.Cells[3].Value);
                }
                LabelUsedDayCount.Text = usedVacations.ToString();
            }
            String selectedEmployee = DataGridViewEmployee.SelectedRows[0].Cells[0].Value.ToString();
            //We must take total vacation day count from dataset, not from numericupdown value!
            //Because it can be changed manually.
            foreach (DataRow dr in _EmployeeDS.Tables[0].Rows)
            {
                if (selectedEmployee.Equals(dr["EmployeeID"].ToString()))
                {
                    totalVacations = Convert.ToInt32(dr["AnnualVacationLimit"].ToString());
                    break;
                }
            }
            remainingVacations = totalVacations - usedVacations;
            
            LabelUsedDayCount.Text = usedVacations.ToString();
            LabelRemDayCount.Text = remainingVacations.ToString();
        }

        private void DataGridViewEmployeeVacations_SelectionChanged(object sender, EventArgs e)
        {            
            DateTimePickerVacationFrom.Value = DateTime.Now;
            DateTimePickerVacationTo.Value = DateTime.Now;
            if (DataGridViewEmployeeVacations.SelectedRows.Count == 0) return;
            if (_VacationDS == null) return;
            DataGridViewRow dgvr = DataGridViewEmployeeVacations.SelectedRows[0];
            DateTimePickerVacationFrom.Value = Convert.ToDateTime(dgvr.Cells[1].Value);
            DateTimePickerVacationTo.Value = Convert.ToDateTime(dgvr.Cells[2].Value);
        }

        private void ButtonDeleteVacation_Click(object sender, EventArgs e)
        {
            if (DataGridViewEmployee.SelectedRows.Count == 0)
            {
                MessageBox.Show("You must select an Employee", "Delete Vacation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (DataGridViewEmployeeVacations.SelectedRows.Count == 0)
            {
                MessageBox.Show("You must select a vacation", "Delete Vacation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            DialogResult result = MessageBox.Show("Are you sure that you want to delete the vacation?", "Delete Vacation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result != DialogResult.Yes) return;

            string vacationId = DataGridViewEmployeeVacations.SelectedRows[0].Cells[0].Value.ToString();
            string EmployeeId = DataGridViewEmployee.SelectedRows[0].Cells[0].Value.ToString();
            try
            {
                string sorgu = "DELETE FROM EmployeeVacations WHERE EmployeeVacationID = " + vacationId;
                if (DB.Uygula(sorgu, "ButtonDeleteVacation_Click"))
                {
                    MessageBox.Show("Vacation deleted.", "Delete Vacation", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    LoadVacations(EmployeeId);
                    ButtonNewVacation_Click(null, null);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occured while deleting vacation!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine(ex.StackTrace);
            }
        }

        private void CheckBoxPeriodFilter1_CheckedChanged(object sender, EventArgs e)
        {
            if (CheckBoxPeriodFilter1.Checked)
            {
                GroupBoxPeriod.Enabled = true;
                GroupBoxDate.Enabled = false;
                CheckBoxPeriodFilter2.Checked = false;
            }
            else if (!CheckBoxPeriodFilter1.Checked)
            {
                GroupBoxPeriod.Enabled = false;
                GroupBoxDate.Enabled = true;
                CheckBoxPeriodFilter2.Checked = true;
            }
        }

        private void CheckBoxPeriodFilter2_CheckedChanged(object sender, EventArgs e)
        {
            if (CheckBoxPeriodFilter2.Checked)
            {
                GroupBoxPeriod.Enabled = false;
                GroupBoxDate.Enabled = true;
                CheckBoxPeriodFilter1.Checked = false;
            }
            else if (!CheckBoxPeriodFilter2.Checked)
            {
                GroupBoxPeriod.Enabled = true;
                GroupBoxDate.Enabled = false;
                CheckBoxPeriodFilter1.Checked = true;
            }
        }
        private bool isPossibleActionsLoaded = false;
        private void DataGridViewActions_SelectionChanged(object sender, EventArgs e)
        {
            isPossibleActionsLoaded = false;
            LoadEmptyPossibleActions();
            if (DataGridViewActions.SelectedRows.Count > 0)
                LoadPossibleActions(DataGridViewActions.SelectedRows[0].Cells[0].Value.ToString());
            isPossibleActionsLoaded = true;
        }

        private void DataGridViewPossibleActions_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1 || e.ColumnIndex == -1 || e.ColumnIndex == 0 || e.ColumnIndex == 2) return;

            //DataGridViewCheckBoxCell curCell = (DataGridViewCheckBoxCell)DataGridViewPossibleActions.Rows[e.RowIndex].Cells[e.ColumnIndex];
            //((DataGridViewCheckBoxCell)curCell.OwningRow.Cells[1]).Value = false;
        }

        private void DataGridViewPossibleActions_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1 || e.ColumnIndex == -1 || isPossibleActionsLoaded == false) return;
            DataGridViewCheckBoxCell curCell = (DataGridViewCheckBoxCell)DataGridViewPossibleActions.Rows[e.RowIndex].Cells[e.ColumnIndex];
            String possibleActionId = curCell.OwningRow.Cells[0].Value.ToString();
            String actionId = DataGridViewActions.SelectedRows[0].Cells[0].Value.ToString();
            int val = Convert.ToInt32(curCell.Value);
            try
            {
                String sql = "";
                if (val == 0)
                {
                    sql = "Delete ActionFlow WHERE FirstActionID = " + actionId + " AND NextActionID = " + possibleActionId;
                }
                else if (val == 1)
                {
                    sql = "INSERT INTO ActionFlow(FirstActionID, NextActionID) VALUES(" + actionId + ", " + possibleActionId + ")";
                }
                if (!DB.Uygula(sql, ""))
                {
                    throw new Exception("DataGridViewPossibleActions_CellValueChanged");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occured while updating the values!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine(ex.StackTrace);
            }
        }
        bool buttonSubmitComplete = false;
        private void ButtonSubmit_Click(object sender, EventArgs e)
        {
            buttonSubmitComplete = false;
            _EmployeeActionsDS = null;

            //creating a datatable for daily actions. It stores only selected day's actions.
            _EmployeeActionsDT = new DataTable("E");
            _EmployeeActionsDT.Columns.Add("ActionId");
            _EmployeeActionsDT.Columns.Add("Time");

            if(DataGridViewEmployeeList.SelectedRows.Count == 0)
            {
                MessageBox.Show("You must select an employee first!", "Employee Actions", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            DateTime startDate = DateTime.Now;
            DateTime endDate = DateTime.Now;
            String employeeId = DataGridViewEmployeeList.SelectedRows[0].Cells[0].Value.ToString();
            DateTime hireDate = startDate;
            foreach (DataRow dr in _EmployeeDS.Tables[0].Rows)
            {
                if (dr["EmployeeID"].ToString().Equals(employeeId))
                {
                    if (!dr["HireDate"].Equals(DBNull.Value))
                    {
                        hireDate = Convert.ToDateTime(dr["HireDate"]);
                        break;
                    }
                }
            }
            String sql = "SELECT * FROM EmployeeDailyActions WHERE EmployeeID = " + employeeId;
            String sqlDatePart = "";
            if (CheckBoxPeriodFilter1.Checked)
            {
                if (RadioButtonAll.Checked)
                {
                    startDate = hireDate;
                }
                else if (RadioButtonYear.Checked)
                {
                    DateTime firstDayOfTheThisYear = Utility.GetFirstDayOfThisYear();
                    if (firstDayOfTheThisYear.CompareTo(hireDate) < 0)
                        firstDayOfTheThisYear = hireDate;
                    sqlDatePart = " AND ActionDate BETWEEN '" + String.Format(@"{0:yyyy-MM-dd 00:00:00}", firstDayOfTheThisYear) + "' ";
                    sqlDatePart += "AND '" + String.Format(@"{0:yyyy-MM-dd 23:59:59}", DateTime.Now) + "' ";
                    startDate = firstDayOfTheThisYear;
                }
                else if (RadioButtonMonth.Checked)
                {
                    DateTime firstDayOfTheThisMonth = Utility.GetFirstDayOfThisMonth();
                    if (firstDayOfTheThisMonth.CompareTo(hireDate) < 0)
                        firstDayOfTheThisMonth = hireDate;
                    sqlDatePart = " AND ActionDate BETWEEN '" + String.Format(@"{0:yyyy-MM-dd 00:00:00}", firstDayOfTheThisMonth) + "' ";
                    sqlDatePart += "AND '" + String.Format(@"{0:yyyy-MM-dd 23:59:59}", DateTime.Now) + "' ";
                    startDate = firstDayOfTheThisMonth;
                }
                else if (RadioButtonWeek.Checked)
                {
                    DateTime firstDayOfTheThisWeek = Utility.GetFirstDayOfWeek(DateTime.Now);
                    if (firstDayOfTheThisWeek.CompareTo(hireDate) < 0)
                        firstDayOfTheThisWeek = hireDate;
                    sqlDatePart = " AND ActionDate BETWEEN '" + String.Format(@"{0:yyyy-MM-dd 00:00:00}", firstDayOfTheThisWeek) + "' ";
                    sqlDatePart += "AND '" + String.Format(@"{0:yyyy-MM-dd 23:59:59}", DateTime.Now) + "' ";
                    startDate = firstDayOfTheThisWeek;
                }
            }
            else //Custom period selected
            {
                //TODO:Check constraints od start and end dates
                startDate = DateTimePickerFrom.Value;
                endDate = DateTimePickerTo.Value;
                if (startDate.CompareTo(endDate) > 0)
                {
                    MessageBox.Show("From Date must be less than To Date", "Employee Actions", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (startDate.CompareTo(hireDate) < 0)
                {
                    startDate = hireDate;
                }
                sqlDatePart = " AND ActionDate BETWEEN '" + String.Format(@"{0:yyyy-MM-dd 00:00:00}", startDate) + "' ";
                sqlDatePart += "AND '" + String.Format(@"{0:yyyy-MM-dd 23:59:59}", endDate) + "' ";
            }

            try
            {
                sql += sqlDatePart + " ORDER BY ActionDate DESC";
                _EmployeeActionsDS = DB.Sorgula(sql, "ButtonSubmit_Click");
                if (_EmployeeActionsDS == null) throw new Exception("");
                DataGridViewEmployeeActions.Rows.Clear();
                if (DataGridViewEmployeeActions.Rows.Count > 0 && RadioButtonYear.Checked)
                    startDate = Convert.ToDateTime(_EmployeeActionsDS.Tables[0].Rows[_EmployeeActionsDS.Tables[0].Rows.Count - 1]["ActionDate"]);
                for (DateTime date = endDate; date >= startDate; date = date.AddDays(-1))
                {
                    DataGridViewEmployeeActions.Rows.Add(String.Format("{0:dd.MM.yyyy ddd}", date));
                }

                foreach (DataRow dr in _EmployeeActionsDS.Tables[0].Rows)
                {
                    foreach (DataGridViewRow dgvr in DataGridViewEmployeeActions.Rows)
                    {
                        if (dgvr.Cells[0].Value.ToString().Equals(String.Format("{0:dd.MM.yyyy ddd}", Convert.ToDateTime(dr["ActionDate"]))))
                        {
                            String exception = "";
                            if (dr["Labour"].Equals(DBNull.Value) || Convert.ToInt32(dr["Operator"]) == 1)
                            {
                                exception = "*";
                            }
                            DateTime total = DateTime.MinValue;
                            if (!dr["Labour"].Equals(DBNull.Value))
                            {
                                total = total.AddMinutes(Convert.ToInt32(dr["Labour"]));
                            }
                            if (!dr["ELabour"].Equals(DBNull.Value))
                            {
                                total = total.AddMinutes(Convert.ToInt32(dr["ELabour"]));
                            }

                            dgvr.Cells[0].Value = String.Format("{0:dd.MM.yyyy ddd}", Convert.ToDateTime(dr["ActionDate"])) + exception;
                            dgvr.Cells[1].Value = dr["Labour"].Equals(DBNull.Value) ? "" : String.Format(@"{0:HH:mm}", total);
                            /*DataGridViewEmployeeActions.Rows.Add(String.Format("{0:dd.MM.yyyy}", Convert.ToDateTime(dr["ActionDate"])) + exception,
                                dr["Labour"].Equals(DBNull.Value) ? "" : String.Format(@"{0:HH:mm}", total)
                                );*/

                            if (!dr["Move1ActionID"].Equals(DBNull.Value))
                            {
                                dgvr.Cells[2].Value = String.Format(@"{0:HH:mm}", dr["Move1ActionTime"]);
                            }
                            if (!dr["Move2ActionID"].Equals(DBNull.Value))
                            {
                                dgvr.Cells[3].Value = String.Format(@"{0:HH:mm}", dr["Move2ActionTime"]);
                            }
                            if (!dr["Move3ActionID"].Equals(DBNull.Value))
                            {
                                dgvr.Cells[4].Value = String.Format(@"{0:HH:mm}", dr["Move3ActionTime"]);
                            }
                            if (!dr["Move4ActionID"].Equals(DBNull.Value))
                            {
                                dgvr.Cells[5].Value = String.Format(@"{0:HH:mm}", dr["Move4ActionTime"]);
                            }
                            if (!dr["Move5ActionID"].Equals(DBNull.Value))
                            {
                                dgvr.Cells[6].Value = String.Format(@"{0:HH:mm}", dr["Move5ActionTime"]);
                            }
                            if (!dr["Move6ActionID"].Equals(DBNull.Value))
                            {
                                dgvr.Cells[7].Value = String.Format(@"{0:HH:mm}", dr["Move6ActionTime"]);
                            }
                            if (!dr["Move7ActionID"].Equals(DBNull.Value))
                            {
                                dgvr.Cells[8].Value = String.Format(@"{0:HH:mm}", dr["Move7ActionTime"]);
                            }
                            if (!dr["Move8ActionID"].Equals(DBNull.Value))
                            {
                                dgvr.Cells[9].Value = String.Format(@"{0:HH:mm}", dr["Move8ActionTime"]);
                            }
                            dgvr.Tag = dr["DailyActionID"].ToString();
                            break;
                        }
                    }
                }

                // CalculateTimeBlocks();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occured while getting in/out values!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine(ex.StackTrace);
            }
            if (DataGridViewEmployeeActions.SelectedRows.Count > 0)
                DataGridViewEmployeeActions.SelectedRows[0].Selected = false;
            buttonSubmitComplete = true;
        }

        private void DataGridViewEmployeeList_SelectionChanged(object sender, EventArgs e)
        {
            DataGridViewEmployeeActions.Rows.Clear();
        }

        private void DataGridViewEmployeeActions_SelectionChanged(object sender, EventArgs e)
        {
            DataGridViewDailyActions.Rows.Clear();
            DataGridViewTotalTime.Rows.Clear();
            LabelDayDescription.Text = "";
            if (buttonSubmitComplete == false) return;
            if (DataGridViewEmployeeActions.SelectedRows.Count == 0)
                return;
            //If tag is null it means that employee has no action 
            if (DataGridViewEmployeeActions.SelectedRows[0].Tag == null)
            {
                String employeeId = DataGridViewEmployeeList.SelectedRows[0].Cells[0].Value.ToString();
                DateTime sd = DateTime.ParseExact(DataGridViewEmployeeActions.SelectedRows[0].Cells[0].Value.ToString(), "dd.MM.yyyy ddd", null);
                String sql = "SELECT * FROM EmployeeVacations WHERE VacationDate = '" + String.Format(@"{0:yyyy-MM-dd 00:00:00}", sd) + "' AND EmployeeID = " + employeeId;
                DataSet ds = DB.Sorgula(sql, "DataGridViewEmployeeActions_SelectionChanged");

                if (ds != null && ds.Tables[0].Rows.Count == 1)
                {
                    LabelDayDescription.Text = "Employee is on vacation.";
                }
                else
                {
                    LabelDayDescription.Text = "Employee has no action.";
                }
                GroupBoxLabourEdit.Enabled = false;
                DateTimePickerLabour.Value = Utility.GetMinDate();
                DateTimePickerELabour.Value = Utility.GetMinDate();
                TextBoxLabourDesc.Text = "";
                return;
            }
            int dailyActionID = Convert.ToInt32(DataGridViewEmployeeActions.SelectedRows[0].Tag.ToString());
            DataRow dailyActionRow = null;
            foreach (DataRow dr in _EmployeeActionsDS.Tables[0].Rows)
            {
                if (dailyActionID == Convert.ToInt32(dr["DailyActionID"]))
                {
                    dailyActionRow = dr;
                    break;
                }
            }

            DateTime selectedDate = Convert.ToDateTime(dailyActionRow["ActionDate"]);
            try
            {
                String sql = "SELECT * FROM DateOfDays WHERE DateOfDay = '" + String.Format(@"{0:yyyy-MM-dd 00:00:00}", selectedDate) + "'";
                DataSet ds = DB.Sorgula(sql, "DataGridViewEmployeeActions_SelectionChanged");
                String dayDescription = "";
                if (ds != null && ds.Tables[0].Rows.Count == 1)
                {
                    if (Convert.ToInt32(ds.Tables[0].Rows[0]["IsFullDay"]) == 1)
                    {
                        dayDescription = "Selected date is a full day.";
                    }
                    else if (Convert.ToInt32(ds.Tables[0].Rows[0]["IsHalfDay"]) == 1)
                    {
                        dayDescription = "Selected date is a half day.";
                    }
                    else if (Convert.ToInt32(ds.Tables[0].Rows[0]["IsHoliday"]) == 1)
                    {
                        dayDescription = "Selected date is a holiday.";
                    }
                    else
                    {
                        dayDescription = "Selected day type must be defined !!!";
                    }
                }
                String employeeId = DataGridViewEmployeeList.SelectedRows[0].Cells[0].Value.ToString();
                sql = "SELECT * FROM EmployeeVacations WHERE VacationDate = '" + String.Format(@"{0:yyyy-MM-dd 00:00:00}", selectedDate) + "' AND EmployeeID = " + employeeId;
                ds = DB.Sorgula(sql, "DataGridViewEmployeeActions_SelectionChanged");

                if (ds != null && ds.Tables[0].Rows.Count == 1)
                {
                    dayDescription += " And employee is on vacation.";
                }

                LabelDayDescription.Text = dayDescription;
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occured!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine(ex.StackTrace);
            }

            DataGridViewTotalTime.Rows.Add("Labour", "");
            DataGridViewTotalTime.Rows.Add("Extra Labour", "");
            DataGridViewTotalTime.Rows.Add("G.Doctor", "");
            DataGridViewTotalTime.Rows.Add("S.Doctor", "");
            DataGridViewTotalTime.Rows.Add("Customer/Vendor", "");
            DataGridViewTotalTime.Rows.Add("Personal Issues", "");

            for (int i = 0; i < 8; i++)
            {
                DataGridViewDailyActions.Rows.Add((i + 1) + ".Move", "", "");
            }

            if (dailyActionRow != null)
            {
                for (int i = 0; i < 8; i++)
                {
                    if (i == 0 && !DBNull.Value.Equals(dailyActionRow["Move1ActionID"]))
                    {
                        DataGridViewDailyActions.Rows[0].Cells[1].Value = String.Format("{0:HH:mm}", dailyActionRow["Move1ActionTime"]);
                        DataGridViewDailyActions.Rows[0].Cells[2].Value = _ActionDS.Tables[0].Select("ActionId = " + dailyActionRow["Move1ActionID"].ToString())[0]["ActionName"].ToString();
                    }
                    if (i == 1 && !DBNull.Value.Equals(dailyActionRow["Move2ActionID"]))
                    {
                        DataGridViewDailyActions.Rows[1].Cells[1].Value = String.Format("{0:HH:mm}", dailyActionRow["Move2ActionTime"]);
                        DataGridViewDailyActions.Rows[1].Cells[2].Value = _ActionDS.Tables[0].Select("ActionId = " + dailyActionRow["Move2ActionID"].ToString())[0]["ActionName"].ToString();
                    }
                    if (i == 2 && !DBNull.Value.Equals(dailyActionRow["Move3ActionID"]))
                    {
                        DataGridViewDailyActions.Rows[2].Cells[1].Value = String.Format("{0:HH:mm}", dailyActionRow["Move3ActionTime"]);
                        DataGridViewDailyActions.Rows[2].Cells[2].Value = _ActionDS.Tables[0].Select("ActionId = " + dailyActionRow["Move3ActionID"].ToString())[0]["ActionName"].ToString();
                    }
                    if (i == 3 && !DBNull.Value.Equals(dailyActionRow["Move4ActionID"]))
                    {
                        DataGridViewDailyActions.Rows[3].Cells[1].Value = String.Format("{0:HH:mm}", dailyActionRow["Move4ActionTime"]);
                        DataGridViewDailyActions.Rows[3].Cells[2].Value = _ActionDS.Tables[0].Select("ActionId = " + dailyActionRow["Move4ActionID"].ToString())[0]["ActionName"].ToString();
                    }
                    if (i == 4 && !DBNull.Value.Equals(dailyActionRow["Move5ActionID"]))
                    {
                        DataGridViewDailyActions.Rows[4].Cells[1].Value = String.Format("{0:HH:mm}", dailyActionRow["Move5ActionTime"]);
                        DataGridViewDailyActions.Rows[4].Cells[2].Value = _ActionDS.Tables[0].Select("ActionId = " + dailyActionRow["Move5ActionID"].ToString())[0]["ActionName"].ToString();
                    }
                    if (i == 5 && !DBNull.Value.Equals(dailyActionRow["Move6ActionID"]))
                    {
                        DataGridViewDailyActions.Rows[5].Cells[1].Value = String.Format("{0:HH:mm}", dailyActionRow["Move6ActionTime"]);
                        DataGridViewDailyActions.Rows[5].Cells[2].Value = _ActionDS.Tables[0].Select("ActionId = " + dailyActionRow["Move6ActionID"].ToString())[0]["ActionName"].ToString();
                    }
                    if (i == 6 && !DBNull.Value.Equals(dailyActionRow["Move7ActionID"]))
                    {
                        DataGridViewDailyActions.Rows[6].Cells[1].Value = String.Format("{0:HH:mm}", dailyActionRow["Move7ActionTime"]);
                        DataGridViewDailyActions.Rows[6].Cells[2].Value = _ActionDS.Tables[0].Select("ActionId = " + dailyActionRow["Move7ActionID"].ToString())[0]["ActionName"].ToString();
                    }
                    if (i == 7 && !DBNull.Value.Equals(dailyActionRow["Move8ActionID"]))
                    {
                        DataGridViewDailyActions.Rows[7].Cells[1].Value = String.Format("{0:HH:mm}", dailyActionRow["Move8ActionTime"]);
                        DataGridViewDailyActions.Rows[7].Cells[2].Value = _ActionDS.Tables[0].Select("ActionId = " + dailyActionRow["Move8ActionID"].ToString())[0]["ActionName"].ToString();
                    }
                }
            }

            if (dailyActionRow != null)
            {
                if (Convert.ToInt32(dailyActionRow["Operator"]) == 1)//admin
                {
                    DataGridViewTotalTime.Rows[0].Cells[1].Value = !DBNull.Value.Equals(dailyActionRow["Labour"]) ? String.Format("{0:HH:mm}", DateTime.MinValue.AddMinutes(Convert.ToInt32(dailyActionRow["Labour"]))) : "";
                    DataGridViewTotalTime.Rows[1].Cells[1].Value = !DBNull.Value.Equals(dailyActionRow["ELabour"]) ? String.Format("{0:HH:mm}", DateTime.MinValue.AddMinutes(Convert.ToInt32(dailyActionRow["ELabour"]))) : "";
                    DateTimePickerLabour.Value = !DBNull.Value.Equals(dailyActionRow["Labour"]) ? Utility.GetMinDate().AddMinutes(Convert.ToInt32(dailyActionRow["Labour"])) : Utility.GetMinDate();
                    DateTimePickerELabour.Value = !DBNull.Value.Equals(dailyActionRow["ELabour"]) ? Utility.GetMinDate().AddMinutes(Convert.ToInt32(dailyActionRow["ELabour"])) : Utility.GetMinDate();
                    TextBoxLabourDesc.Text = !DBNull.Value.Equals(dailyActionRow["Description"]) ? dailyActionRow["Description"].ToString() : "";
                    GroupBoxLabourEdit.Enabled = true;
                }
                else
                {
                    if (!DBNull.Value.Equals(dailyActionRow["Labour"]))//Daily actions are legal and job calculated labour time
                    {
                        GroupBoxLabourEdit.Enabled = false;
                        DateTimePickerLabour.Value = Utility.GetMinDate();
                        DateTimePickerELabour.Value = Utility.GetMinDate();
                        TextBoxLabourDesc.Text = "";

                        DataGridViewTotalTime.Rows[0].Cells[1].Value = String.Format("{0:HH:mm}", DateTime.MinValue.AddMinutes(Convert.ToInt32(dailyActionRow["Labour"])));
                        if (!DBNull.Value.Equals(dailyActionRow["ELabour"]))
                            DataGridViewTotalTime.Rows[1].Cells[1].Value = String.Format("{0:HH:mm}", DateTime.MinValue.AddMinutes(Convert.ToInt32(dailyActionRow["ELabour"])));
                        if (!DBNull.Value.Equals(dailyActionRow["GenDoc"]))
                            DataGridViewTotalTime.Rows[2].Cells[1].Value = String.Format("{0:HH:mm}", DateTime.MinValue.AddMinutes(Convert.ToInt32(dailyActionRow["GenDoc"])));
                        if (!DBNull.Value.Equals(dailyActionRow["SpeDoc"]))
                            DataGridViewTotalTime.Rows[3].Cells[1].Value = String.Format("{0:HH:mm}", DateTime.MinValue.AddMinutes(Convert.ToInt32(dailyActionRow["SpeDoc"])));
                        if (!DBNull.Value.Equals(dailyActionRow["CusVen"]))
                            DataGridViewTotalTime.Rows[4].Cells[1].Value = String.Format("{0:HH:mm}", DateTime.MinValue.AddMinutes(Convert.ToInt32(dailyActionRow["CusVen"])));
                        if (!DBNull.Value.Equals(dailyActionRow["PerIss"]))
                            DataGridViewTotalTime.Rows[5].Cells[1].Value = String.Format("{0:HH:mm}", DateTime.MinValue.AddMinutes(Convert.ToInt32(dailyActionRow["PerIss"])));
                    }
                    else
                    {
                        GroupBoxLabourEdit.Enabled = true;
                        DateTimePickerLabour.Value = Utility.GetMinDate();
                        DateTimePickerELabour.Value = Utility.GetMinDate();
                        TextBoxLabourDesc.Text = "";
                    }
                }
            }
        }

        private void FormAdminMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            //thread1.Abort();
            //thread1.Join();
        }

        class Employee
        {
            public int employeeID;
            public ArrayList dailyActions;
        }

        class DailyAction
        {
            public DateTime date;
            public ArrayList actions;
        }

        class Action
        {
            public int actionID;
            public int employeeActionID;
            public DateTime actionTime;
        }

        class EmployeeDailyAction
        {
            public int employeeID;
            public DateTime actionDate;
            public int move1ActionID;
            public DateTime move1ActionTime;
            public int move2ActionID;
            public DateTime move2ActionTime;
            public int move3ActionID;
            public DateTime move3ActionTime;
            public int move4ActionID;
            public DateTime move4ActionTime;
            public int move5ActionID;
            public DateTime move5ActionTime;
            public int move6ActionID;
            public DateTime move6ActionTime;
            public int move7ActionID;
            public DateTime move7ActionTime;
            public int move8ActionID;
            public DateTime move8ActionTime;
            public int labour;
            public int eLabour;
            public int genDoc;
            public int speDoc;
            public int cusVen;
            public int perIss;

            public EmployeeDailyAction()
            {
                employeeID = -1;
                actionDate = DateTime.MinValue;
                move1ActionID = -1;
                move1ActionTime = DateTime.MinValue;
                move2ActionID = -1;
                move2ActionTime = DateTime.MinValue;
                move3ActionID = -1;
                move3ActionTime = DateTime.MinValue;
                move4ActionID = -1;
                move4ActionTime = DateTime.MinValue;
                move5ActionID = -1;
                move5ActionTime = DateTime.MinValue;
                move6ActionID = -1;
                move6ActionTime = DateTime.MinValue;
                move7ActionID = -1;
                move7ActionTime = DateTime.MinValue;
                move8ActionID = -1;
                move8ActionTime = DateTime.MinValue;
                labour = 0;
                eLabour = 0;
                genDoc = 0;
                speDoc = 0;
                cusVen = 0;
                perIss = 0;
            }
        }

        private void DataGridViewEmployee_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1 && e.ColumnIndex == -1)
            {
                FormAdminMain_Load(null, null);
            }
        }

        private void ButtonLabourSave_Click(object sender, EventArgs e)
        {
            if (DataGridViewEmployeeActions.SelectedRows.Count == 0)
            {
                MessageBox.Show("You must select a row from Employee Actions Grid first!", "Save Labour/Extra Labour", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            //TODO:check constraints of labour and extra labour times

            String description = TextBoxLabourDesc.Text.Trim();
            int labourMinutes = DateTimePickerLabour.Value.Hour * 60 + DateTimePickerLabour.Value.Minute;
            int eLabourMinutes = DateTimePickerELabour.Value.Hour * 60 + DateTimePickerELabour.Value.Minute;
            int dailyActionID = Convert.ToInt32(DataGridViewEmployeeActions.SelectedRows[0].Tag.ToString());
            try
            {
                String sql = "UPDATE EmployeeDailyActions SET Labour = " + labourMinutes + ", ELabour = " + eLabourMinutes + ", Description = '" + description + "', Operator = 1 WHERE DailyActionID = " + dailyActionID;
                if (!DB.Uygula(sql, "ButtonLabourSave_Click")) throw new Exception();
                else
                {
                    MessageBox.Show("Labour/Extra Labour saved!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ButtonSubmit_Click(null, null);
                    foreach (DataGridViewRow dgrv in DataGridViewEmployeeActions.Rows)
                    {
                        if (dgrv.Tag != null && dgrv.Tag.ToString() == dailyActionID.ToString())
                        {
                            dgrv.Selected = true;
                            DataGridViewEmployeeActions.FirstDisplayedScrollingRowIndex = dgrv.Index;
                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occured while saving labour/extra labour times", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine(ex.StackTrace);
            }
        }

        private void DataGridViewEmployeeList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1 && e.ColumnIndex == -1)
            {
                InOutTabLoad();
            }
        }

        private void ButtonDailyActionReport_Click(object sender, EventArgs e)
        {
            if (DataGridViewEmployeeActions.Rows.Count == 0)
            {
                MessageBox.Show("There is no data to show report.\nSearch something first", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            DailyActionsRpt rpt = new DailyActionsRpt();
            try
            {
                DailyActionsDS ds = new DailyActionsDS();

                foreach (DataGridViewRow dgvr in DataGridViewEmployeeActions.Rows)
                {
                    ds.DailyActionsDT.AddDailyActionsDTRow(dgvr.Cells[0].Value != null ? dgvr.Cells[0].Value.ToString() : "",
                                                           dgvr.Cells[1].Value != null ? dgvr.Cells[1].Value.ToString() : "",
                                                           dgvr.Cells[2].Value != null ? dgvr.Cells[2].Value.ToString() : "",
                                                           dgvr.Cells[3].Value != null ? dgvr.Cells[3].Value.ToString() : "",
                                                           dgvr.Cells[4].Value != null ? dgvr.Cells[4].Value.ToString() : "",
                                                           dgvr.Cells[5].Value != null ? dgvr.Cells[5].Value.ToString() : "",
                                                           dgvr.Cells[6].Value != null ? dgvr.Cells[6].Value.ToString() : "",
                                                           dgvr.Cells[7].Value != null ? dgvr.Cells[7].Value.ToString() : "",
                                                           dgvr.Cells[8].Value != null ? dgvr.Cells[8].Value.ToString() : "",
                                                           dgvr.Cells[9].Value != null ? dgvr.Cells[9].Value.ToString() : "",
                                                           "");
                }

                String employeeID = DataGridViewEmployeeList.SelectedRows[0].Cells[0].Value.ToString();
                String name = "", department = "", manager = "", email = "", phone = "", code = "";
                foreach (DataRow dr in _EmployeeDS.Tables[0].Rows)
                {
                    if (dr["EmployeeID"].ToString().Equals(employeeID))
                    {
                        name = dr["NameSurname"] != DBNull.Value ? dr["NameSurname"].ToString() : "";
                        email = dr["Email"] != DBNull.Value ? dr["Email"].ToString() : "";
                        phone = dr["PhoneNumber"] != DBNull.Value ? dr["PhoneNumber"].ToString() : "";
                        code = dr["Code"] != DBNull.Value ? dr["Code"].ToString() : "";
                        if (dr["ManagerID"] != DBNull.Value)
                        {
                            foreach (DataRow drs in _EmployeeDS.Tables[0].Rows)
                            {
                                if (drs["EmployeeID"].ToString().Equals(dr["ManagerID"].ToString()))
                                {
                                    manager = drs["NameSurname"].ToString();
                                    break;
                                }
                            }
                        }
                        if (dr["DepartmentID"] != DBNull.Value)
                        {
                            foreach (DataRow drs in _DepartmentDS.Tables[0].Rows)
                            {
                                if (drs["DepartmentID"].ToString().Equals(dr["DepartmentID"].ToString()))
                                {
                                    department = drs["DepartmentName"].ToString();
                                    break;
                                }
                            }
                        }
                        TimeSpan labourTS = new TimeSpan();
                        TimeSpan elabourTS = new TimeSpan();
                        TimeSpan cusvenTS = new TimeSpan();
                        TimeSpan perissTS = new TimeSpan();
                        TimeSpan gdocTS = new TimeSpan();
                        TimeSpan sdocTS = new TimeSpan();

                        int i = 0;
                        foreach (DataGridViewRow dgvr in DataGridViewEmployeeActions.Rows)
                        {
                            dgvr.Selected = true;
                            Application.DoEvents();

                            if (DataGridViewTotalTime.Rows.Count == 0) continue;
                            String labour = DataGridViewTotalTime.Rows[0].Cells[1].Value.ToString();
                            String elabour = DataGridViewTotalTime.Rows[1].Cells[1].Value.ToString();
                            String cusven = DataGridViewTotalTime.Rows[4].Cells[1].Value.ToString();
                            String periss = DataGridViewTotalTime.Rows[5].Cells[1].Value.ToString();
                            String gdoc = DataGridViewTotalTime.Rows[2].Cells[1].Value.ToString();
                            String sdoc = DataGridViewTotalTime.Rows[3].Cells[1].Value.ToString();

                            if (!labour.Equals(""))
                            {
                                labourTS = labourTS.Add(new TimeSpan(Convert.ToInt32(labour.Split(':')[0]), Convert.ToInt32(labour.Split(':')[1]), 0));
                            }
                            if (!elabour.Equals(""))
                            {
                                elabourTS = elabourTS.Add(new TimeSpan(Convert.ToInt32(elabour.Split(':')[0]), Convert.ToInt32(elabour.Split(':')[1]), 0));
                            }
                            if (!cusven.Equals(""))
                            {
                                cusvenTS = cusvenTS.Add(new TimeSpan(Convert.ToInt32(cusven.Split(':')[0]), Convert.ToInt32(cusven.Split(':')[1]), 0));
                            }
                            if (!periss.Equals(""))
                            {
                                perissTS = perissTS.Add(new TimeSpan(Convert.ToInt32(periss.Split(':')[0]), Convert.ToInt32(periss.Split(':')[1]), 0));
                            }
                            if (!gdoc.Equals(""))
                            {
                                gdocTS = gdocTS.Add(new TimeSpan(Convert.ToInt32(gdoc.Split(':')[0]), Convert.ToInt32(gdoc.Split(':')[1]), 0));
                            }
                            if (!sdoc.Equals(""))
                            {
                                sdocTS = sdocTS.Add(new TimeSpan(Convert.ToInt32(sdoc.Split(':')[0]), Convert.ToInt32(sdoc.Split(':')[1]), 0));
                            }
                            ds.DailyActionsDT.Rows[i][10] = TextBoxLabourDesc.Text;
                            i++;
                        }
                        ds.TotalActionsDT.AddTotalActionsDTRow(labourTS.Days * 24 + labourTS.Hours + ":" + labourTS.Minutes,
                                                               elabourTS.Days * 24 + elabourTS.Hours + ":" + elabourTS.Minutes,
                                                               gdocTS.Days * 24 + gdocTS.Hours + ":" + gdocTS.Minutes,
                                                               sdocTS.Days * 24 + sdocTS.Hours + ":" + sdocTS.Minutes,
                                                               cusvenTS.Days * 24 + cusvenTS.Hours + ":" + cusvenTS.Minutes,
                                                               perissTS.Days * 24 + perissTS.Hours + ":" + perissTS.Minutes);

                        String desc = TextBoxLabourDesc.Text;
                        break;
                    }
                }

                ds.EmployeeDT.Rows.Add(name, department, manager, email, phone, code);

                rpt.SetDataSource(ds);
                FormReport frm = new FormReport();
                frm.setReport(rpt);
                frm.ShowDialog(this);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Couldn't generate report!");
                return;
            }
            finally
            {
                rpt.Dispose();
            }
        }



    }
}












////The job1 starts on application loading.
////It calculates the employees labour time per day
////and writes the result to the db.
//private void StartJob1()
//{
//    try
//    {
//        //load action flows
//        DataSet actionFlowDS = null;
//        String sql  = "SELECT * from dbo.ActionFlow";
//        actionFlowDS = DB.Sorgula(sql, "");

//        if(actionFlowDS == null)
//        {
//            LogJobStatus(1, DateTime.Now, 0, "Could not retrieve data from ActionFlow table");
//            return;
//        }

//        sql = "SELECT MAX(LastProcessTime) FROM JobLog WHERE IsSuccessful = 1";
//        DataSet ds = DB.Sorgula(sql, "StartJob1");
//        if (ds == null)
//        {
//            LogJobStatus(1, DateTime.Now, 0, "Could not retrieve data from JobLog table");
//            return;
//        }

//        //get appropriate start date for searching EmployeeActions table
//        DateTime maxDate = Utility.GetMinDate();
//        if (!ds.Tables[0].Rows[0][0].Equals(DBNull.Value))
//        {
//            maxDate = Convert.ToDateTime(ds.Tables[0].Rows[0][0].ToString());
//        }
//        else//this is job's first time running
//        {
//            sql = "SELECT MIN(ActionTime) FROM EmployeeActions";
//            ds = DB.Sorgula(sql, "StartJob1");
//            if (ds == null)
//            {
//                LogJobStatus(1, DateTime.Now, 0, "Could not retrieve data from JobLog table");
//                return;
//            }
//            if (!ds.Tables[0].Rows[0][0].Equals(DBNull.Value))
//            {
//                maxDate = Convert.ToDateTime(ds.Tables[0].Rows[0][0].ToString());
//            }
//            else//There is no data in table
//            {
//                LogJobStatus(1, DateTime.Now, 0, "There is no data in EmployeeActions table");
//                return;
//            }
//        }

//        sql = "SELECT * FROM Employees WHERE IsDeleted = 0";
//        DataSet employeeDS = DB.Sorgula(sql, "StartJob1");
//        if(employeeDS == null)
//        {
//            LogJobStatus(1, DateTime.Now, 0, "Could not retrieve data from Employees table");
//            return;
//        }
//        if (employeeDS.Tables[0].Rows.Count == 0)
//        {
//            LogJobStatus(1, DateTime.Now, 0, "There is no employee in Employees table");
//            return;
//        }

//        TimeSpan f_pl_s = new TimeSpan();//Full Day Pre Labour Start Time 
//        TimeSpan f_pl_e = new TimeSpan();//Full Day Pre Labour End Time 
//        TimeSpan f_i_s = new TimeSpan();//Full Day Flexible Entrance Start Time 
//        TimeSpan f_i_e = new TimeSpan();//Full Day Flexible Entrance End Time 
//        TimeSpan f_m_s = new TimeSpan();//Full Day Morning Start Time 
//        TimeSpan f_m_e = new TimeSpan();//Full Day Morning End Time 
//        TimeSpan f_l_s = new TimeSpan();//Full Day Flexible Entrance Lunch Start Time 
//        TimeSpan f_l_e = new TimeSpan();//Full Day Flexible Entrance Lunch End Time 
//        TimeSpan f_a_s = new TimeSpan();//Full Day Afternoon Labour Start Time 
//        TimeSpan f_a_e = new TimeSpan();//Full Day Afternoon Labour End Time 
//        TimeSpan f_o_s = new TimeSpan();//Full Day Flexible Out Start Time 
//        TimeSpan f_o_e = new TimeSpan();//Full Day Flexible Out End Time 
//        TimeSpan f_al_s = new TimeSpan();//Full Day After Labour Start Time 
//        TimeSpan f_al_e = new TimeSpan();//Full Day After Labour End Time 

//        TimeSpan h_pl_s = new TimeSpan();//Half Day Pre Labour Start Time 
//        TimeSpan h_pl_e = new TimeSpan();//Half Day Pre Labour End Time 
//        TimeSpan h_i_s = new TimeSpan();//Half Day Flexible Entrance Start Time 
//        TimeSpan h_i_e = new TimeSpan();//Half Day Flexible Entrance End Time 
//        TimeSpan h_m_s = new TimeSpan();//Half Day Morning Start Time 
//        TimeSpan h_m_e = new TimeSpan();//Half Day Morning End Time 
//        TimeSpan h_lo_s = new TimeSpan();//Half Day Flexible Entrance Lunch and flexible out Start Time 
//        TimeSpan h_lo_e = new TimeSpan();//Half Day Flexible Entrance Lunch and flexible out End Time 
//        TimeSpan h_a_s = new TimeSpan();//Half Day Afternoon Labour Start Time 
//        TimeSpan h_a_e = new TimeSpan();//Half Day Afternoon Labour End Time 
//        TimeSpan h_o_s = new TimeSpan();//Half Day Flexible Out Start Time 
//        TimeSpan h_o_e = new TimeSpan();//Half Day Flexible Out End Time 
//        TimeSpan h_l_s = new TimeSpan();//Half Day After Labour Start Time 
//        TimeSpan h_l_e = new TimeSpan();//Half Day After Labour End Time 


//        sql = "SELECT * FROM TimeBlocks";
//        DataSet timeBlockDS = DB.Sorgula(sql, "StartJob1");
//        if(timeBlockDS == null)
//        {
//            LogJobStatus(1, DateTime.Now, 0, "Could not retrieve data from TimeBlocks table");
//            return;
//        }
//        foreach (DataRow dr in timeBlockDS.Tables[0].Rows)
//        {
//            if (dr["IsFull"].ToString().Equals("True"))
//            {
//                if (dr["TimeCode"].ToString().Equals("PL"))
//                {
//                    f_pl_s = TimeSpan.Parse(dr["TimePeriodFrom"].ToString());
//                    f_pl_e = TimeSpan.Parse(dr["TimePeriodTo"].ToString());
//                }
//                else if (dr["TimeCode"].ToString().Equals("I"))
//                {
//                    f_i_s = TimeSpan.Parse(dr["TimePeriodFrom"].ToString());
//                    f_i_e = TimeSpan.Parse(dr["TimePeriodTo"].ToString());
//                }
//                else if (dr["TimeCode"].ToString().Equals("M"))
//                {
//                    f_m_s = TimeSpan.Parse(dr["TimePeriodFrom"].ToString());
//                    f_m_e = TimeSpan.Parse(dr["TimePeriodTo"].ToString());
//                }
//                else if (dr["TimeCode"].ToString().Equals("L"))
//                {
//                    f_l_s = TimeSpan.Parse(dr["TimePeriodFrom"].ToString());
//                    f_l_e = TimeSpan.Parse(dr["TimePeriodTo"].ToString());
//                }
//                else if (dr["TimeCode"].ToString().Equals("A"))
//                {
//                    f_a_s = TimeSpan.Parse(dr["TimePeriodFrom"].ToString());
//                    f_a_e = TimeSpan.Parse(dr["TimePeriodTo"].ToString());
//                }
//                else if (dr["TimeCode"].ToString().Equals("O"))
//                {
//                    f_o_s = TimeSpan.Parse(dr["TimePeriodFrom"].ToString());
//                    f_o_e = TimeSpan.Parse(dr["TimePeriodTo"].ToString());
//                }
//                else if (dr["TimeCode"].ToString().Equals("AL"))
//                {
//                    f_al_s = TimeSpan.Parse(dr["TimePeriodFrom"].ToString());
//                    f_al_e = TimeSpan.Parse(dr["TimePeriodTo"].ToString());
//                }
//            }
//            else
//            {
//                if (dr["TimeCode"].ToString().Equals("PL"))
//                {
//                    h_pl_s = TimeSpan.Parse(dr["TimePeriodFrom"].ToString());
//                    h_pl_e = TimeSpan.Parse(dr["TimePeriodTo"].ToString());
//                }
//                else if (dr["TimeCode"].ToString().Equals("I"))
//                {
//                    h_i_s = TimeSpan.Parse(dr["TimePeriodFrom"].ToString());
//                    h_i_e = TimeSpan.Parse(dr["TimePeriodTo"].ToString());
//                }
//                else if (dr["TimeCode"].ToString().Equals("M"))
//                {
//                    h_m_s = TimeSpan.Parse(dr["TimePeriodFrom"].ToString());
//                    h_m_e = TimeSpan.Parse(dr["TimePeriodTo"].ToString());
//                }
//                else if (dr["TimeCode"].ToString().Equals("LO"))
//                {
//                    h_lo_s = TimeSpan.Parse(dr["TimePeriodFrom"].ToString());
//                    h_lo_e = TimeSpan.Parse(dr["TimePeriodTo"].ToString());
//                }
//                else if (dr["TimeCode"].ToString().Equals("A"))
//                {
//                    h_a_s = TimeSpan.Parse(dr["TimePeriodFrom"].ToString());
//                    h_a_e = TimeSpan.Parse(dr["TimePeriodTo"].ToString());
//                }
//                else if (dr["TimeCode"].ToString().Equals("O"))
//                {
//                    h_o_s = TimeSpan.Parse(dr["TimePeriodFrom"].ToString());
//                    h_o_e = TimeSpan.Parse(dr["TimePeriodTo"].ToString());
//                }
//                else if (dr["TimeCode"].ToString().Equals("L"))
//                {
//                    h_l_s = TimeSpan.Parse(dr["TimePeriodFrom"].ToString());
//                    h_l_e = TimeSpan.Parse(dr["TimePeriodTo"].ToString());
//                }
//            }
//        }

//        DateTime jobMaxDate = Utility.GetMinDate();
//        //start calculating
//        for (DateTime date = maxDate; date.CompareTo(DateTime.Now) <= 0; date = date.AddDays(1))
//        {
//            //check DateOfDays for related date 
//            //if the related date is not defined return
//            sql = "SELECT * FROM DateOfDays WHERE DateOfDay = '" + String.Format(@"{0:yyyy-MM-dd 00:00:00}", date) + "'";
//            ds = DB.Sorgula(sql, "StartJob1");
//            if (ds != null && ds.Tables[0].Rows.Count != 1)
//            {
//                LogJobStatus(1, DateTime.Now, 0, String.Format(@"{0:yyyy-MM-dd}", date) + " is not defined in DateOfDays table");
//                return;
//            }
//            jobMaxDate = Utility.GetOnlyDate(date);
//            ArrayList employees = new ArrayList();
//            foreach (DataRow edr in employeeDS.Tables[0].Rows)
//            {
//                String currentEmployee = edr["EmployeeID"].ToString();
//                DateTime hireDate = Convert.ToDateTime(edr["HireDate"]);

//                if (hireDate.CompareTo(date) > 0)
//                {
//                    continue;   
//                }
//                //Check if employee is on vacation on that date

//                sql = "SELECT * FROM EmployeeVacations WHERE EmployeeID = " + currentEmployee + " AND VacationDate = '" + String.Format("{0:yyyy-MM-dd}", date) + "'";
//                ds = DB.Sorgula(sql, "StartJob1");
//                if (ds == null)
//                {
//                    LogJobStatus(1, date, 0, "Could not retrieve data from EmployeeVacations table");
//                    return;
//                }
//                if (ds.Tables[0].Rows.Count > 0)//employee is on vacation
//                {
//                    continue;
//                }
//                sql = @"SELECT * FROM EmployeeActions WHERE ActionTime BETWEEN '" + String.Format(@"{0:yyyy-MM-dd 00:00:00}", date) +
//                      @"' AND '" + String.Format(@"{0:yyyy-MM-dd 23:59:59}", date) + "' AND EmployeeID = " + currentEmployee + " order by cast(floor(cast(ActionTime as float)) as datetime) asc, ActionTime asc;";
//                ds = DB.Sorgula(sql, "StartJob1");
//                if (ds == null)
//                {
//                    LogJobStatus(1, date, 0, "Could not retrieve data from EmployeeActions table");
//                    return;
//                }
//                if (ds.Tables[0].Rows.Count > 0)
//                {
//                    foreach (DataRow dr in ds.Tables[0].Rows)
//                    {
//                        String currentDate = Convert.ToDateTime(dr["ActionTime"]).ToShortDateString();
//                        if (Convert.ToDateTime(dr["ActionTime"]).CompareTo(jobMaxDate) > 0)
//                            jobMaxDate = Convert.ToDateTime(dr["ActionTime"]);
//                        Employee employee = null;
//                        DailyAction dailyAction = null;
//                        foreach (Employee e in employees)
//                        {
//                            if (e.employeeID.ToString().Equals(currentEmployee))
//                            {
//                                employee = e;
//                                break;
//                            }
//                        }
//                        if (employee != null)
//                        {
//                            foreach (DailyAction da in employee.dailyActions)
//                            {
//                                if (currentDate.Equals(da.date.ToShortDateString()))
//                                {
//                                    dailyAction = da;
//                                    break;
//                                }
//                            }
//                            if (dailyAction != null)
//                            {
//                                Action action = new Action();
//                                action.employeeActionID = Convert.ToInt32(dr["EmployeeActionID"]);
//                                action.actionID = Convert.ToInt32(dr["ActionID"]);
//                                action.actionTime = Convert.ToDateTime(dr["ActionTime"]);
//                                dailyAction.actions.Add(action);
//                            }
//                            else
//                            {
//                                Action action = new Action();
//                                action.employeeActionID = Convert.ToInt32(dr["EmployeeActionID"]);
//                                action.actionID = Convert.ToInt32(dr["ActionID"]);
//                                action.actionTime = Convert.ToDateTime(dr["ActionTime"]);
//                                dailyAction = new DailyAction();
//                                dailyAction.date = Utility.GetOnlyDate(Convert.ToDateTime(dr["ActionTime"]));
//                                dailyAction.actions = new ArrayList();
//                                dailyAction.actions.Add(action);
//                                employee.dailyActions.Add(dailyAction);
//                            }
//                        }
//                        else
//                        {
//                            employee = new Employee();
//                            employee.employeeID = Convert.ToInt32(currentEmployee);
//                            employee.dailyActions = new ArrayList();


//                            Action action = new Action();
//                            action.employeeActionID = Convert.ToInt32(dr["EmployeeActionID"]);
//                            action.actionID = Convert.ToInt32(dr["ActionID"]);
//                            action.actionTime = Convert.ToDateTime(dr["ActionTime"]);
//                            dailyAction = new DailyAction();
//                            dailyAction.date = Utility.GetOnlyDate(Convert.ToDateTime(dr["ActionTime"]));
//                            dailyAction.actions = new ArrayList();
//                            dailyAction.actions.Add(action);
//                            employee.dailyActions.Add(dailyAction);
//                            employees.Add(employee);
//                        }
//                    }

//                    if (employees.Count > 0)
//                    {
//                        foreach (Employee emp in employees)
//                        {
//                            foreach (DailyAction da in emp.dailyActions)
//                            {
//                                EmployeeDailyAction eda = new EmployeeDailyAction();
//                                eda.employeeID = emp.employeeID;
//                                eda.actionDate = da.date;
//                                sql = @"SELECT * FROM EmployeeDailyActions where ActionDate = '" + String.Format(@"{0:yyyy-MM-dd 00:00:00}", da.date) + "' AND EmployeeID = " + emp.employeeID;
//                                DataSet dataSet = DB.Sorgula(sql, "");
//                                bool dailyActionExits = true;
//                                bool isOperatorAdmin = false;
//                                if (dataSet.Tables[0].Rows.Count == 0)
//                                {
//                                    dailyActionExits = false;
//                                }
//                                else
//                                {
//                                    if (Convert.ToInt32(dataSet.Tables[0].Rows[0]["Operator"]) == 0)
//                                    {
//                                        isOperatorAdmin = false;
//                                    }
//                                }
//                                int s = 0;
//                                foreach (Action action in da.actions)
//                                {
//                                    if (s == 0)
//                                    {
//                                        eda.move1ActionID = action.actionID;
//                                        eda.move1ActionTime = action.actionTime;
//                                    }
//                                    else if (s == 1)
//                                    {
//                                        eda.move2ActionID = action.actionID;
//                                        eda.move2ActionTime = action.actionTime;
//                                    }
//                                    else if (s == 2)
//                                    {
//                                        eda.move3ActionID = action.actionID;
//                                        eda.move3ActionTime = action.actionTime;
//                                    }
//                                    else if (s == 3)
//                                    {
//                                        eda.move4ActionID = action.actionID;
//                                        eda.move4ActionTime = action.actionTime;
//                                    }
//                                    else if (s == 4)
//                                    {
//                                        eda.move5ActionID = action.actionID;
//                                        eda.move5ActionTime = action.actionTime;
//                                    }
//                                    else if (s == 5)
//                                    {
//                                        eda.move6ActionID = action.actionID;
//                                        eda.move6ActionTime = action.actionTime;
//                                    }
//                                    else if (s == 6)
//                                    {
//                                        eda.move7ActionID = action.actionID;
//                                        eda.move7ActionTime = action.actionTime;
//                                    }
//                                    else if (s == 7)
//                                    {
//                                        eda.move8ActionID = action.actionID;
//                                        eda.move8ActionTime = action.actionTime;
//                                    }
//                                    s++;
//                                }
//                                //calculate labour time
//                                if (da.actions.Count % 2 == 0)
//                                {
//                                    if (da.actions.Count == 4)//suppose that 1)In morning 2)out lunch 3)in lunch 4)out exit
//                                    {
//                                        if (((Action)da.actions[0]).actionID == _InMorning &&
//                                           ((Action)da.actions[1]).actionID == _OutLunch &&
//                                           ((Action)da.actions[2]).actionID == _InLunch &&
//                                           ((Action)da.actions[3]).actionID == _OutExit)
//                                        {
//                                            Action inMorningAction = (Action)da.actions[0];
//                                            Action outLunchAction = (Action)da.actions[1];
//                                            Action inLunchAction = (Action)da.actions[2];
//                                            Action outExitAction = (Action)da.actions[3];

//                                            TimeSpan el = new TimeSpan(), l = new TimeSpan();
//                                            if (inMorningAction.actionTime.TimeOfDay < f_i_s)
//                                            {
//                                                el = f_i_s.Subtract(inMorningAction.actionTime.TimeOfDay);
//                                                l = outLunchAction.actionTime.TimeOfDay.Subtract(f_i_s);
//                                            }
//                                            else
//                                            {
//                                                l = outLunchAction.actionTime.TimeOfDay.Subtract(inMorningAction.actionTime.TimeOfDay);
//                                            }

//                                            if (outExitAction.actionTime.TimeOfDay > f_al_s)
//                                            {
//                                                el = el.Add(outExitAction.actionTime.TimeOfDay.Subtract(f_al_s));
//                                                l = l.Add(f_al_s.Subtract(inLunchAction.actionTime.TimeOfDay));
//                                            }
//                                            else
//                                            {
//                                                l = l.Add(outExitAction.actionTime.TimeOfDay.Subtract(inLunchAction.actionTime.TimeOfDay));
//                                            }


//                                            /*TimeSpan beforeLunch = outLunchAction.actionTime.Subtract(inMorningAction.actionTime);
//                                            TimeSpan afterLunch = outExitAction.actionTime.Subtract(inLunchAction.actionTime);
//                                            TimeSpan totalLabour = beforeLunch.Add(afterLunch);
//                                            int labour = totalLabour.Hours * 60 + totalLabour.Minutes;
//                                            eda.labour = labour;*/
//                                            eda.labour = l.Hours * 60 + l.Minutes;
//                                            eda.eLabour = el.Hours * 60 + el.Minutes;
//                                        }
//                                    }
//                                    else if (da.actions.Count == 6 || da.actions.Count == 8)
//                                    {
//                                        if (((Action)da.actions[0]).actionID == _InMorning && ((Action)da.actions[da.actions.Count - 1]).actionID == _OutExit)
//                                        {

//                                            bool isLegal = true;
//                                            //check actionflows
//                                            for (int j = 0; j <= (da.actions.Count - 1); j++)
//                                            {
//                                                int actionId = ((Action)da.actions[j]).actionID;
//                                                //if it is not the last action.
//                                                //because we check the last action on previous step
//                                                if (j != (da.actions.Count - 1))
//                                                {
//                                                    int nextActionId = ((Action)da.actions[j + 1]).actionID;
//                                                    int len = actionFlowDS.Tables[0].Select("FirstActionId = " + actionId + " AND NextActionId = " + nextActionId).Length;
//                                                    if (len == 0)//it is not a legal action. because the action pair not defined.
//                                                    {
//                                                        //Daily actions are not legal
//                                                        isLegal = false;
//                                                        break;
//                                                    }
//                                                }
//                                            }
//                                            if (isLegal)
//                                            {
//                                                DateTime inMorning = DateTime.MinValue, inPersonal = DateTime.MinValue, inGenDoc = DateTime.MinValue, inSpeDoc = DateTime.MinValue, inCusVen = DateTime.MinValue, inLunch = DateTime.MinValue;
//                                                DateTime outExit = DateTime.MinValue, outPersonal = DateTime.MinValue, outGenDoc = DateTime.MinValue, outSpeDoc = DateTime.MinValue, outCusVen = DateTime.MinValue, outLunch = DateTime.MinValue;


//                                                foreach (Action action in da.actions)
//                                                {
//                                                    if (action.actionID == _InMorning)
//                                                        inMorning = action.actionTime;
//                                                    else if (action.actionID == _InSpecialPersonal)
//                                                        inPersonal = action.actionTime;
//                                                    else if (action.actionID == _InSpecialGenDoctor)
//                                                        inGenDoc = action.actionTime;
//                                                    else if (action.actionID == _InSpecialSpeDoctor)
//                                                        inSpeDoc = action.actionTime;
//                                                    else if (action.actionID == _InSpecialCustomerVendor)
//                                                        inCusVen = action.actionTime;
//                                                    else if (action.actionID == _InLunch)
//                                                        inLunch = action.actionTime;
//                                                    else if (action.actionID == _OutExit)
//                                                        outExit = action.actionTime;
//                                                    else if (action.actionID == _OutSpecialPersonal)
//                                                        outPersonal = action.actionTime;
//                                                    else if (action.actionID == _OutSpecialGenDoctor)
//                                                        outGenDoc = action.actionTime;
//                                                    else if (action.actionID == _OutSpecialSpeDoctor)
//                                                        outSpeDoc = action.actionTime;
//                                                    else if (action.actionID == _OutSpecialCustomerVendor)
//                                                        outCusVen = action.actionTime;
//                                                    else if (action.actionID == _OutLunch)
//                                                        outLunch = action.actionTime;


//                                                }

//                                                //lunch actions must exists
//                                                if (inLunch.CompareTo(DateTime.MinValue) != 0 && outLunch.CompareTo(DateTime.MinValue) != 0)
//                                                {
//                                                    //TimeSpan lunch = inLunch.Subtract(outLunch);
//                                                    TimeSpan inOut = outExit.Subtract(inMorning);
//                                                    TimeSpan genDoc = inGenDoc.Subtract(outGenDoc);
//                                                    TimeSpan speDoc = inSpeDoc.Subtract(outSpeDoc);
//                                                    TimeSpan perIss = inPersonal.Subtract(outPersonal);
//                                                    TimeSpan cusVen = inCusVen.Subtract(outCusVen);

//                                                    TimeSpan el = new TimeSpan(), l = new TimeSpan();
//                                                    if (inMorning.TimeOfDay < f_i_s)
//                                                    {
//                                                        el = f_i_s.Subtract(inMorning.TimeOfDay);
//                                                        l = outLunch.TimeOfDay.Subtract(f_i_s);
//                                                    }
//                                                    else
//                                                    {
//                                                        l = outLunch.TimeOfDay.Subtract(inMorning.TimeOfDay);
//                                                    }

//                                                    if (outExit.TimeOfDay > f_al_s)
//                                                    {
//                                                        el = el.Add(outExit.TimeOfDay.Subtract(f_al_s));
//                                                        l = l.Add(f_al_s.Subtract(inLunch.TimeOfDay));
//                                                    }
//                                                    else
//                                                    {
//                                                        l = l.Add(outExit.TimeOfDay.Subtract(inLunch.TimeOfDay));
//                                                    }

//                                                    l = l.Subtract(genDoc).Subtract(speDoc).Subtract(perIss);

//                                                    eda.labour = l.Hours * 60 + l.Minutes;
//                                                    eda.eLabour = el.Hours * 60 + el.Minutes;
//                                                    eda.genDoc = genDoc.Hours * 60 + genDoc.Minutes;
//                                                    eda.speDoc = speDoc.Hours * 60 + speDoc.Minutes;
//                                                    eda.perIss = perIss.Hours * 60 + perIss.Minutes;
//                                                    eda.cusVen = cusVen.Hours * 60 + cusVen.Minutes;
//                                                }
//                                            }
//                                        }
//                                    }
//                                }
//                                ProcessEmployeeDailyAction(eda, dailyActionExits, isOperatorAdmin);
//                            }
//                        }
//                    }
//                } 
//            }
//            LogJobStatus(1, jobMaxDate, 1, "");
//        }

//    }
//    catch (Exception ex)
//    {
//        Console.WriteLine(ex.StackTrace);
//        LogJobStatus(1, DateTime.Now, 0, ex.StackTrace);
//        thread1.Abort();
//    }
//}

//private void ProcessEmployeeDailyAction(EmployeeDailyAction eda, bool dailyActionExits, bool isOperatorAdmin)
//{
//    String sql = @"";
//    if (dailyActionExits)
//    {
//        sql = @"UPDATE EmployeeDailyActions SET Move1ActionID = " + eda.move1ActionID + ", Move1ActionTime = '" + String.Format(@"{0:yyyy-MM-dd HH:mm:ss}", eda.move1ActionTime) + "'";
//        if (eda.move2ActionID != -1)
//        {
//            sql += @", Move2ActionID = " + eda.move2ActionID + ", Move2ActionTime = '" + String.Format(@"{0:yyyy-MM-dd HH:mm:ss}", eda.move2ActionTime) + "'";
//        }
//        if (eda.move3ActionID != -1)
//        {
//            sql += @", Move3ActionID = " + eda.move3ActionID + ", Move3ActionTime = '" + String.Format(@"{0:yyyy-MM-dd HH:mm:ss}", eda.move3ActionTime) + "'";
//        }
//        if (eda.move4ActionID != -1)
//        {
//            sql += @", Move4ActionID = " + eda.move4ActionID + ", Move4ActionTime = '" + String.Format(@"{0:yyyy-MM-dd HH:mm:ss}", eda.move4ActionTime) + "'";
//        }
//        if (eda.move5ActionID != -1)
//        {
//            sql += @", Move5ActionID = " + eda.move5ActionID + ", Move5ActionTime = '" + String.Format(@"{0:yyyy-MM-dd HH:mm:ss}", eda.move5ActionTime) + "'";
//        }
//        if (eda.move6ActionID != -1)
//        {
//            sql += @", Move6ActionID = " + eda.move6ActionID + ", Move6ActionTime = '" + String.Format(@"{0:yyyy-MM-dd HH:mm:ss}", eda.move6ActionTime) + "'";
//        }
//        if (eda.move7ActionID != -1)
//        {
//            sql += @", Move7ActionID = " + eda.move7ActionID + ", Move7ActionTime = '" + String.Format(@"{0:yyyy-MM-dd HH:mm:ss}", eda.move7ActionTime) + "'";
//        }
//        if (eda.move8ActionID != -1)
//        {
//            sql += @", Move8ActionID = " + eda.move8ActionID + ", Move8ActionTime = '" + String.Format(@"{0:yyyy-MM-dd HH:mm:ss}", eda.move8ActionTime) + "'";
//        }

//        if (eda.labour != 0)
//        {
//            if (!isOperatorAdmin)
//            {
//                sql += ", Labour = " + eda.labour;
//            }
//        }
//        if (eda.eLabour != 0)
//        {
//            if (!isOperatorAdmin)
//            {
//                sql += ", ELabour = " + eda.eLabour;
//            }
//        }
//        if (eda.genDoc != 0)
//        {
//            sql += ", GenDoc = " + eda.genDoc;
//        }
//        if (eda.speDoc != 0)
//        {
//            sql += ", SpeDoc = " + eda.speDoc;
//        }
//        if (eda.perIss != 0)
//        {
//            sql += ", PerIss = " + eda.perIss;
//        }
//        if (eda.cusVen != 0)
//        {
//            sql += ", CusVen = " + eda.cusVen;
//        }

//        sql += " WHERE EmployeeID = " + eda.employeeID + " AND ActionDate = '" + String.Format(@"{0:yyyy-MM-dd 00:00:00}", eda.actionDate) + "'";
//        DB.Uygula(sql, "ProcessEmployeeDailyAction");
//    }
//    else
//    {
//        String sql1 = @"INSERT INTO EmployeeDailyActions(EmployeeID, ActionDate, Move1ActionID, Move1ActionTime";
//        String sql2 = @") VALUES(" + eda.employeeID + ", '" + String.Format(@"{0:yyyy-MM-dd 00:00:00}", eda.actionDate) + "', " + eda.move1ActionID + ", '" + String.Format(@"{0:yyyy-MM-dd HH:mm:ss}", eda.move1ActionTime) + "'";


//        if (eda.move2ActionID != -1)
//        {
//            sql1 += @", Move2ActionID, Move2ActionTime";
//            sql2 += @", " + eda.move2ActionID + ", '" + String.Format(@"{0:yyyy-MM-dd HH:mm:ss}", eda.move2ActionTime) + "'";
//        }
//        if (eda.move3ActionID != -1)
//        {
//            sql1 += @", Move3ActionID, Move3ActionTime";
//            sql2 += @", " + eda.move3ActionID + ", '" + String.Format(@"{0:yyyy-MM-dd HH:mm:ss}", eda.move3ActionTime) + "'";
//        }
//        if (eda.move4ActionID != -1)
//        {
//            sql1 += @", Move4ActionID, Move4ActionTime";
//            sql2 += @", " + eda.move4ActionID + ", '" + String.Format(@"{0:yyyy-MM-dd HH:mm:ss}", eda.move4ActionTime) + "'";
//        }
//        if (eda.move5ActionID != -1)
//        {
//            sql1 += @", Move5ActionID, Move5ActionTime";
//            sql2 += @", " + eda.move5ActionID + ", '" + String.Format(@"{0:yyyy-MM-dd HH:mm:ss}", eda.move5ActionTime) + "'";
//        }
//        if (eda.move6ActionID != -1)
//        {
//            sql1 += @", Move6ActionID, Move6ActionTime";
//            sql2 += @", " + eda.move6ActionID + ", '" + String.Format(@"{0:yyyy-MM-dd HH:mm:ss}", eda.move6ActionTime) + "'";
//        }
//        if (eda.move7ActionID != -1)
//        {
//            sql1 += @", Move7ActionID, Move7ActionTime";
//            sql2 += @", " + eda.move7ActionID + ", '" + String.Format(@"{0:yyyy-MM-dd HH:mm:ss}", eda.move7ActionTime) + "'";
//        }
//        if (eda.move8ActionID != -1)
//        {
//            sql1 += @", Move8ActionID, Move8ActionTime";
//            sql2 += @", " + eda.move8ActionID + ", '" + String.Format(@"{0:yyyy-MM-dd HH:mm:ss}", eda.move8ActionTime) + "'";
//        }

//        if (eda.labour != 0)
//        {
//            sql1 += @", Labour";
//            sql2 += @", " + eda.labour;          
//        }
//        if (eda.eLabour != 0)
//        {
//            sql1 += @", ELabour";
//            sql2 += @", " + eda.eLabour;
//        }
//        if (eda.genDoc != 0)
//        {
//            sql1 += @", GenDoc";
//            sql2 += @", " + eda.genDoc; 
//        }
//        if (eda.speDoc != 0)
//        {
//            sql1 += @", SpeDoc";
//            sql2 += @", " + eda.speDoc; 
//        }
//        if (eda.perIss != 0)
//        {
//            sql1 += @", PerIss";
//            sql2 += @", " + eda.perIss; 
//        }
//        if (eda.cusVen != 0)
//        {
//            sql1 += @", CusVen";
//            sql2 += @", " + eda.cusVen; 
//        }
//        sql = sql1 + sql2 + ")";
//        DB.Uygula(sql, "ProcessEmployeeDailyAction");
//    }
//}

//private void LogJobStatus(int jobID, DateTime time, int success, String description)
//{
//    description = Utility.InputFilter(description);
//    if (description.Length > 500)
//        description = description.Substring(0, 500);
//    string sql = @"INSERT INTO JobLog(JobID, LastProcessTime, IsSuccessful, Description) VALUES(" + 
//        jobID + ", '" + String.Format(@"{0:yyyy-MM-dd HH:mm:ss}", time) + "', " + success + ", '" + description + "')";
//    DB.Uygula(sql, "LogJobStatus");
//}